package com.yonhee.arithmetic.recursion;

public class BinarySearch {
    public static int search(int[] arr, int target) {
        return binarySearchRecursion(arr, target, 0, arr.length - 1);
    }

    /**
     * 递归方式实现的二分查找
     * @param arr 数组
     * @param target 目标
     * @param i 低位
     * @param j 高位
     * @return 所在索引
     */
    public static int binarySearchRecursion(int[] arr, int target, int i, int j) {
        if (i > j) {
            return -1;
        }
        int mid = (i + j) >>> 1;
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            return binarySearchRecursion(arr, target, mid + 1, j );
        } else {
            return binarySearchRecursion(arr, target, i, mid - 1);
        }
    }
}
